using Castle.DynamicProxy;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Win32;
using xjjxmm.infrastructure.ToolKit;
using xjjxmm.infrastructure.ToolKit.IdKit;
using XjjXmm.Infrastructure.Ioc;
using XjjXmm.Infrastructure.User;

namespace xjjxmm.infrastructure.xjjxmmLog.AuditLog;

public class AuditLogAttribute : Attribute
{
    public string Action { get; set; }
}

public class AuditLogIdAttribute : Attribute
{

}

public class AuditLogFliterAttribute : Attribute, IAsyncActionFilter
{
    //private readonly IUserContext userContext;

    public string Action { get; set; }
    /*public AuditLogFliter(IUserContext userContext)
    {
        this.userContext = userContext;
    }*/


    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
       
        IUserContextAccessor userContextAccessor = IocManager.Instance.GetService<IUserContextAccessor>();

        UserContext userContext = userContextAccessor.UserContext;

        var registId = context.ActionArguments
            .Select(t => t.Value?.GetValueHaveCustomAttribute<AuditLogIdAttribute>())
            .FirstOrDefault(t => t != null);

        var auditLog = new AuditLog
        {
            Id = SnowFlakeKit.NextIdStr(),
            ActionId = Action,
            RegistId = registId?.ToString(),
            UserId = userContext.Id,
            UserName = userContext.NickName,
            //TentantId 
            // TentantName 
            RequestData = context.ActionArguments,
            RequestTime = DateTime.Now
        };

        ActionExecutedContext executedContext = await next();

        auditLog.ResponseData = executedContext.Result;
        auditLog.ResponseTime = DateTime.Now;

        //var a = "";
    }
}